import random
import re
from django.contrib.auth import login, authenticate, logout
from rest_framework.response import Response
from utils.aliyun_sms import send_sms_code
from rest_framework.views import APIView
# from django.shortcuts import render
# from django.views import View
# Create your views here.
from django_redis import get_redis_connection
from libs.captcha.captcha import captcha
from django.http import HttpResponse, JsonResponse
# from libs.sms_code.smsCode import send_code
from apps.user.models import User
from utils.qiniuyun import qiniu_upload
from utils.name import usercheck


# 图片验证码
class ImageCodeView(APIView):
    def get(self, request):
        image_code_id = request.GET.get('cur')
        # 生成图片验证码
        text, image = captcha.generate_captcha()
        # 保存图片验证码
        redis_conn = get_redis_connection('code')
        redis_conn.setex('img_%s' % image_code_id, 300, text)
        print(text)
        # 响应图片验证码
        return HttpResponse(image, content_type='image/jpeg')


# 短信验证码
class SmsCodeView(APIView):
    def post(self, request):
        # 获取用户输入的手机号和图片验证码
        mobile = request.data.get('mobile')
        image_code = request.data.get('text')
        image_code_id = request.data.get('id')
        # 校验参数
        if not ['mobile', 'image_code']:
            return JsonResponse({"errno": '400', "errmsg": "缺少参数"})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({"errno": '4103', "errmsg": "手机号不合格"})
        # 获取数据库中的图片验证码
        redis_cli = get_redis_connection('code')
        redis_image = redis_cli.get('img_%s' % image_code_id)
        # 校验图片验证码
        if not redis_image or redis_image.decode().lower() != image_code.lower():
            return JsonResponse({"errno": 4103, "errmsg": "图片验证码错误"})
        # 生成随机短信验证码
        code = random.randint(1000, 9999)
        # 短信验证码保存到redis
        redis_cli.setex(mobile, 300, code)
        # 阿里云发送手机验证码
        send_sms_code(mobile, code)
        print(code)
        return JsonResponse({"code": 0, "errmsg": "成功"})


# 注册
class RegisterView(APIView):
    def post(self, request):
        # 获取参数
        mobile = request.data.get('mobile')
        password = request.data.get('password')
        phoneCode = request.data.get('phonecode')
        # 校验参数
        if not [mobile, password, phoneCode]:
            return JsonResponse({"code": 400, "errmsg": "缺少参数"})

        redis_cli = get_redis_connection('code')
        redis_code = redis_cli.get(mobile)

        if not redis_code or phoneCode != redis_code.decode():
            return JsonResponse({"code": 400, "errmsg": "验证码错误"})

        user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        login(request, user)
        return JsonResponse({"code": 0, "errmsg": "登录成功"})


# 登录和退出
class LoginView(APIView):
    # 登录操作
    def post(self, request):
        mobile = request.data.get('mobile')
        password = request.data.get('password')

        if not all([mobile, password]):
            return JsonResponse({"code": 400, "errmsg": "缺少参数"})

        try:
            User.USERNAME_FIELD = 'mobile'
            user = authenticate(username=mobile, password=password)
        except Exception as e:
            print(e)
            user = None
        if not user:
            return Response({"errno": "4106", "errmsg": "密码错误"})
        login(request, user)
        request.session.set_expiry(None)
        a1 = Response({"errno": '0', "errmsg": "成功"})
        return a1

    # 判断用户是否登录
    def get(self, request):
        user = request.user
        if not user.is_authenticated:
            return JsonResponse({
                "errno": "4101",
                "errmsg": "未登录"
            })
        return JsonResponse({
            "errno": "0",
            "errmsg": "已登录",
            "data": {
                "name": user.username,
                'user_id': user.id
            }
        })

    # 退出登录
    def delete(self, request):
        logout(request)

        return JsonResponse({
            "errno": "0",
            "errmsg": "已登出"
        })


# 展示主页
class HomePageView(APIView):
    def get(self, request):
        user = request.user
        if not user.is_authenticated:
            return JsonResponse({"errno": "4101", "errmsg": "未登录"})
        if not user.is_active:
	        return JsonResponse({"errno": '4001', "errmsg": "未上传头像"})
        return JsonResponse({
            "data": {
                "avatar_url": 'http://s5yc6o2h0.hd-bkt.clouddn.com/' + request.user.avatar,
                "create_time": 'user.create_tame',
                "mobile": user.mobile,
                "name": user.username,
                "user_id": user.id
            },
            "errmsg": "OK",
            "errno": "0"
        })


# 上传图片
class HeadPortraitView(APIView):
    def post(self, request):
        # 获取数据
        user_img = request.data.get('avatar')
        # 上传七牛云
        ret, info = qiniu_upload(user_img)
        if info.status_code != 200:
            return JsonResponse({"errno": "4101", "errmsg": "参数错误"})
        request.user.avatar = ret.get('key')
        request.user.save()
        res = {
            "data": {
                "avatar_url": 'http://s5yc6o2h0.hd-bkt.clouddn.com/' + request.user.avatar
            },
            "errno": "0",
            "errmsg": "头像上传成功"
        }

        return JsonResponse(res)


# 修改名字
class RevNameView(APIView):
    def put(self, request):
        name = request.data.get('name')
        request.user.username = name
        request.user.save()
        return JsonResponse({
            "errno": "0",
            "errmsg": "修改成功"
        })


# 实名认证
class AuthView(APIView):
    def post(self, request):
        name = request.data.get('real_name')
        card = request.data.get('id_card')
        aa = usercheck(name, card)

        if aa.get('respCode') != '0000':
            return JsonResponse({
                "errno": "4101",
                "errmsg": "身份证号错误"
            })
        request.user.real_name = name
        request.user.id_card = card
        request.user.save()
        return JsonResponse({
            "errno": "0",
            "errmsg": "实名认证成功"
        })

    def get(self, request):
        real_name = request.user.real_name
        id_card = request.user.id_card
        if not all([real_name, id_card]):
            return JsonResponse({
                "errno": "4101",
                "errmsg": "未实名认证"
            })
        return JsonResponse({
            "errno": "0",
            "data": {
                "real_name": real_name,
                "id_card": id_card
            }
        })



from apps.house.models import House
from apps.user.seralizer import MyHouseSerializer
# 我的房屋列表
class MyHomeView(APIView):
    def get(self, request):
        house = House.objects.filter(user=request.user)
        list1 = []
        for i in house:
            list1.append({
                "address": i.address,
                "area_name": i.area.name,
                "ctime": i.create_time,
                "house_id": i.id,
                "img_url": 'http://s5yc6o2h0.hd-bkt.clouddn.com/' + i.index_image_url,
                "order_count": i.order_count,
                "price": i.price,
                "room_count": i.room_count,
                "title": i.title,
                "user_avatar": 'http://s5yc6o2h0.hd-bkt.clouddn.com/' + i.user.avatar
            })
        return JsonResponse({
            "data": {
                "houses": list1
            },
            "errmsg": "ok",
            "errno": "0"
        })
